package com.definesys.smecrailtransit.module.RealTime;

import android.content.Context;

import com.definesys.smecrailtransit.SmecManager.SmecRetrofit.BaseSubscriber;
import com.definesys.smecrailtransit.SmecManager.SmecRetrofit.HttpResult;
import com.definesys.smecrailtransit.base.SmecBasePresenter;
import com.definesys.smecrailtransit.module.RealTime.bean.RealTimeBean;
import com.definesys.smecrailtransit.utils.CommonUtils;

import java.util.ArrayList;
import java.util.HashMap;

import io.realm.RealmResults;
import rx.Observable;

/**
 * Created by xupeizuo on 2017/7/20.
 */

public class RealTimePresenter extends SmecBasePresenter implements RealTimeContract {

    public RealTimePresenter(Context mContext) {
        super(mContext);
    }

    @Override
    public void getRealTime(HashMap<String, String> map) {
        Observable<HttpResult<ArrayList<RealTimeBean>>> observable=smecRailService.realTime(map);
        schedulerThread(observable).subscribe(new BaseSubscriber<HttpResult<ArrayList<RealTimeBean>>>() {
            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mRxbus.post(RealTimeFragment.GET_REAL_TIME_FAILURE,new Object());
            }

            @Override
            public void onNext(HttpResult<ArrayList<RealTimeBean>> arrayListHttpResult) {
                ArrayList<RealTimeBean> arrayList=arrayListHttpResult.getData();
                mRxbus.post(RealTimeFragment.GET_REAL_TIME_HEADER_SCUUESS,arrayList);
            }
        });
    }

    @Override
    public ArrayList<RealTimeBean> getRealTimeBeanFromRealm() {
        RealmResults<RealTimeBean> realTimeBeanRealmResults=(RealmResults<RealTimeBean>)realmManager.findAll(RealTimeBean.class);
        if(realTimeBeanRealmResults == null){
            return null;
        }
        return (ArrayList<RealTimeBean>)realmManager.getRealm().copyFromRealm(realTimeBeanRealmResults);
    }

    @Override
    public void saveDataToRealm(ArrayList<RealTimeBean> arrayList) {
        realmManager.deleteRealmObject(RealTimeBean.class);
        if(CommonUtils.notEmpty(arrayList)){
            if(arrayList.size()<=20){
                realmManager.insertOrUpdateBatch(arrayList);
            }else {
                for(int i =0;i<20;i++){
                    realmManager.insertOrUpdate(arrayList.get(i));
                }
            }
        }
    }

}
